<?php
define("IS_MAIN", true);
require "./modules/set.php";

header("Content-Type:application/json;charset=utf8");
if ($_SERVER["REQUEST_METHOD"] != "POST") {
	echo '{"code":"error","msg":"只允许POST请求方法"}';
	exit;
}
$rowdata = file_get_contents("php://input");
$query = json_decode($rowdata, true);

if (!(isset($query["code"]) && isset($query["pic"]) && isset($query["describe"]) && isset($query["name"]) && isset($query["user"]))) {
	echo '{"code":"error","msg":"缺少参数"}';
	exit;
}

function getMimeFromDataUrl($dataUrl)
{
	// 正则表达式匹配 Data URL 的 MIME 类型部分  
	if (preg_match('/^data:([\w\/\+-]+);/', $dataUrl, $matches)) {
		return $matches[1]; // 返回 MIME 类型  
	}
	return null; // 如果没有匹配到 MIME 类型，则返回 null  
}
if (!((getMimeFromDataUrl($query["pic"]) == "image/png") && ((getMimeFromDataUrl($query["code"]) == "application/zip") || getMimeFromDataUrl($query["code"]) == "application/x-zip-compressed"))) {
	echo '{"code":"error","msg":"文件格式错误"}';
	exit;
}

function writeDataFromDataUrl($dataUrl, $outputFilePath)
{
	// 解析 Data URL  
	if (preg_match('/^data:(.+?);base64,(.*)$/', $dataUrl, $matches)) {
		$mimeType = $matches[1]; // MIME 类型  
		$base64Data = $matches[2]; // Base64 编码的数据  

		// Base64 解码  
		$decodedData = base64_decode($base64Data);

		// 写入文件  
		if (file_put_contents($outputFilePath, $decodedData)) {
			return true; // 写入成功  
		} else {
			return false; // 写入失败  
		}
	} else {
		return false; // 无效的 Data URL  
	}
}

function getFileSizeFromDataUrl($dataUrl)
{
	// 匹配 Data URL 的格式
	if (preg_match('/^data:(.*?);base64,(.*)$/', $dataUrl, $matches)) {
		// 解码 Base64 数据
		$base64Data = $matches[2];
		$decodedData = base64_decode($base64Data, true);

		// 检查解码是否成功
		if ($decodedData !== false) {
			// 返回文件大小（字节）
			return strlen($decodedData) / 1024576;
		}
	}

	// 如果无法解析 Data URL 或解码失败，则返回 0 或 false
	return 0; // 或者你可以返回 false 表示错误
}

if (!((getFileSizeFromDataUrl($query["pic"]) < 1) && (getFileSizeFromDataUrl($query["code"]) < 5))) {
	echo '{"code":"error","msg":"文件过大"}';
	exit;
}

$u = [];

$conn = mysqli_connect($app["sql"]["host"], $app["sql"]["user"], $app["sql"]["password"], $app["sql"]["dbname"], $app["sql"]["port"]);
try {
	$user = $query["user"];

	$prepare = $conn->prepare("select * from users where id=?");

	$prepare->bind_param("s", $user["id"]);

	$prepare->execute();
	$res = $prepare->get_result();
	if ($res->num_rows == 0) {
		trigger_error("e", E_USER_ERROR);
	}
	$row = $res->fetch_assoc();
	if ($row["password"] != $user["password"]) {
		trigger_error("e", E_USER_ERROR);
	}
	global $u;
	$u = $row;
} catch (Exception $e) {
	echo '{"code":"error","msg":"鉴权失败"}';
	exit;
}

$pd = dirname(__DIR__) . "/projects";
$projects_id = scandir($pd);
unset($projects_id[array_search(".", $projects_id)]);
unset($projects_id[array_search("..", $projects_id)]);
$id = (count($projects_id) + 1) . "";
mkdir($pd . "/" . $id, 0775, true);
$dir = $pd . "/" . $id;
file_put_contents($dir . "/ban.txt", 'false');
file_put_contents($dir . "/author.txt", $u["id"]);
file_put_contents($dir . "/describe.txt", $query["describe"]);
file_put_contents($dir . "/name.txt", $query["name"]);
file_put_contents($dir . "/time.txt", time() . "");
writeDataFromDataUrl($query["pic"], $dir . "/pic.png");
writeDataFromDataUrl($query["code"], $dir . "/code.zip");

echo '{"code": "success"}';
